package com.ry.est.service.impl;

import com.ry.est.dao.ModelDao;
import com.ry.est.dto.ModelDTO;
import com.ry.est.dto.ModelDetailDTO;
import com.ry.est.dto.PageResult;
import com.ry.est.entity.Model;
import com.ry.est.service.ModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ry
 * @since 2021-11-05 12:18
 **/
@Service
public class ModelServiceImpl implements ModelService {
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private ModelDao modelDao;

    @Value("${oss.aliyun}")
    private String ossUrl;

    @Override
    public List<ModelDTO> listBy(Model model, Integer pageIndex, Integer pageSize) {
        Integer offset = (pageIndex - 1) *pageSize;
        List<Model> models = modelDao.listByPage(model, offset, pageSize);
        List<ModelDTO> modelDTOS = models.stream().map(entity -> {
            ModelDTO modelDTO = new ModelDTO();
            modelDTO.setId(entity.getId());
            modelDTO.setModelName(entity.getModelName());
            modelDTO.setFaceImg(ossUrl+entity.getFaceImg());

            return modelDTO;
        }).collect(Collectors.toList());

        return modelDTOS;
    }

    @Override
    public PageResult<ModelDTO> listByPage(Model model,
                                           Integer pageIndex,
                                           Integer pageSize) {
        //查询符合条件的数量
        int count = modelDao.countBy(model);
        PageResult<ModelDTO> pageResult = new PageResult<>(5, count);
        pageResult.setPageNo(pageIndex);
        //数量为0，不往下走
        if (count == 0){
            return pageResult;
        }
        //查符合条件的数据
        List<ModelDTO> modelDTOS = listBy(model,pageIndex,pageSize);

        pageResult.setList(modelDTOS);

        return pageResult;
    }

    @Override
    public ModelDetailDTO getById(Long id) {
        Model model = modelDao.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(model)){
            return null;
        }
        ModelDetailDTO modelDetailDTO = new ModelDetailDTO();
        modelDetailDTO.setId(model.getId());
        modelDetailDTO.setModelName(model.getModelName());
        modelDetailDTO.setFaceImg(ossUrl + model.getFaceImg());
        modelDetailDTO.setContentImg(ossUrl + model.getContentImg());

        return modelDetailDTO;
    }
}
